package com.bsb.base.common.util;

import java.io.IOException;

import net.sf.json.JSONObject;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	public static String toJson(Object object) {
		ObjectMapper mapper = new ObjectMapper();
		String json = "";
		try {
			json = mapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return json;
	}

	@SuppressWarnings("static-access")
	public static JSONObject str2Obj(String jsonStr) {
		JSONObject json = new JSONObject();
		return json.fromObject(jsonStr);
	}

	/**
	 * JSONObject字符串转换成对象
	 * 
	 * @param jsonString
	 *            需要转换的字符串
	 * @param type
	 *            需要转换的对象类型
	 * @return 对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T fromJson(String jsonString, Class<T> type) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		return (T) JSONObject.toBean(jsonObject, type);
	}
	/**
	 * Jackson 字符串转对象
	 * @param jsonString
	 * @param type
	 * @return
	 */
	public static<T> T json2Bean(String jsonString, Class<T> type){
		ObjectMapper mapper = new ObjectMapper();
		T convertValue = null;
		try {
			convertValue = mapper.readValue(jsonString, type);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return convertValue;
	}
	
}
